﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Xml;
using System.Collections;


namespace Telephone
{
    class MdiMenu
    {
        const string filename = "telephone.xml";
        static int pos;
       // create menu
        static void Menu()
        {
            Console.WriteLine("          =========================================================");
            Console.WriteLine("          ||            CHUC NANG DANH BA DIEN THOAI             ||");
            Console.WriteLine("          ||=====================================================||");
            Console.WriteLine("          ||  1. Them moi thue bao...                            ||");
            Console.WriteLine("          ||      2. Sua thong tin thue bao...                   ||");
            Console.WriteLine("          ||          3. Xoa thue bao...                         ||");
            Console.WriteLine("          ||              4. Tim kiem theo ten...                ||");
            Console.WriteLine("          ||                  5. Tim kiem theo so dien thoai...  ||");
            Console.WriteLine("          ||                      6. Xem danh sach thue bao...   ||");
            Console.WriteLine("          ||                          7. Thoat...                ||");
            Console.WriteLine("          =========================================================");
            Console.Write("Chon chuc nang:");
        }

        // create file xml
        static void CreateFile()
        {
            XmlTextWriter write = new XmlTextWriter(filename, Encoding.UTF8);
            write.WriteStartDocument(true);
            write.Formatting = Formatting.Indented;
            write.Indentation = 5;
            write.WriteStartElement("contacts");           
            write.WriteEndElement();
            write.WriteEndDocument();
            write.Close();
        }
      
       
        //=================================================================================================
        static string insertdata(string state,List<Phone> listphone)
        {
            int i = 0,number = 0;
            string _Name, _Code, _Address,array;
            loopname:
            do
            {
                if (i > 0)
                {
                    if (i == 1)
                        Console.Write("\tTen thue bao khong qua 30 ky tu!\n");
                    Console.Write("\t\tNhap lai ten : ");
                }
                else

                    Console.Write("Moi nhap ten : ");
                _Name = Console.ReadLine();
                i++;
            }
            while (_Name.Length > 30);
            if((state=="add")&&(_Name.Length==0))
                goto loopname;

            i = 0;
            //code
            loopcode:
            do
            {
                if (i > 0)
                {
                    if (i == 1)
                        Console.Write("\tMa vung thue bao khong qua 5 ky tu!\n");
                    Console.Write("\t\tNhap lai ma vung : ");
                }
                else
                    Console.Write(" Moi nhap ma vung : ");
                _Code = Console.ReadLine();
                i++;
            }
            while (_Code.Length > 5);
            if((state=="add")&&(_Code.Length==0))
                goto loopcode;
            //address
            i = 0;
            loopaddress:
            do
            {
                if (i > 0)
                {
                    if (i == 1)
                        Console.Write("\tDia chi thue bao khong qua 50 ky tu!\n");
                    Console.Write("\t\tNhap lai dia chi : ");
                }
                else
                    Console.Write(" Moi nhap dia chi : ");
                _Address = Console.ReadLine();
                i++;
            }
            while (_Address.Length > 50);
            if ((state == "add") && (_Address.Length == 0))
                goto loopaddress;
            //number
            i = 0;
            insertphonenumber:
            do
            {
                try
                {
                    if (i > 0)
                    {
                        if (i == 1)
                            Console.Write("\tSo dien thoai nam trong khoang 4000000->4999999!\n");
                        Console.Write("\t\tNhap lai so dien thoai : ");
                    }
                    else
                        Console.Write(" Moi nhap so dien thoai : ");
                    i++;
                    number = Convert.ToInt32(Console.ReadLine());
                }
                catch (Exception ex)
                {
                }
            }
            while (number < 4000000 || number > 4999999);
            foreach (Phone phone in listphone)
            {
                if (number == Convert.ToInt32(phone.Number))
                    goto insertphonenumber;
            }
            array = _Name + "," + _Code + "," + _Address + "," + number.ToString();
            return array;
        }
        // insert one element into file xml
        static public void FuntionAdd()
        {
            string _Name, _Code, _Address,_Number, choose, oldarray;
            List<Phone> listphone = XmlToList(filename);
            oldarray = insertdata("add",listphone);
            string[] array = oldarray.Split(',');
            _Name = array[0];
            _Code = array[1];
            _Address = array[2];
            _Number = array[3];
            
             string msgQuestionInsert = " Ban co dong y them moi thue bao khong(Y/N?):";

             Console.Write(msgQuestionInsert);
             choose = Console.ReadKey().KeyChar.ToString();
             if ((choose == "y") || (choose == "Y"))
             {
                 Phone phone = new Phone(_Name, _Code, _Address, _Number);
                 listphone.Add(phone);                 
                 CreateFile();
                 ListToXml(listphone);
                 Console.WriteLine("\nThem moi thanh cong");
             }
             if ((choose == "n") || (choose == "N"))
             {
                 Console.Clear();
                 Menu();
             }
        }
        //==========
        // add one node to file xml
        public static void add(Phone phone,string _filename)
        {
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(_filename);
            
            XmlElement nodephone= myDoc.CreateElement("Phone");
            XmlElement phoneName = myDoc.CreateElement("Name");
            XmlElement phoneCode = myDoc.CreateElement("Code");
            XmlElement phoneAddress = myDoc.CreateElement("Address");
            XmlElement PhoneNumber = myDoc.CreateElement("Number");

            phoneName.InnerText = phone.Name;
            phoneCode.InnerText = phone.Code;
            phoneAddress.InnerText = phone.Address;
            PhoneNumber.InnerText = phone.Number;

            nodephone.AppendChild(phoneName);
            nodephone.AppendChild(phoneCode);
            nodephone.AppendChild(phoneAddress);
            nodephone.AppendChild(PhoneNumber);
            myDoc.DocumentElement.AppendChild(nodephone);

            myDoc.Save(_filename);
        }
        //===========
        // convert from list to file xml
        public static void ListToXml(List<Phone> listphone)
        {
            listphone= Sort(listphone);
            Display(listphone);
            foreach (Phone phone in listphone)
            {
                add(phone,filename);
            }
        }
        //========
        // convert from file xml to list
        public static List<Phone> XmlToList(string _filename)
        {
            List<Phone> listphone = new List<Phone>();
            XmlDocument doc = new XmlDocument();
            doc.Load(_filename);          
            XmlNodeList nodelist = doc.GetElementsByTagName("Name");
            int i = 0;
                foreach (XmlNode node in nodelist)
                {
                    string _name, _code, _address, _number;
                    XmlNode nodecode = doc.GetElementsByTagName("Code")[i];
                    XmlNode nodeaddress = doc.GetElementsByTagName("Address")[i];
                    XmlNode nodenumber = doc.GetElementsByTagName("Number")[i];

                    _name = node.ChildNodes[0].Value;
                    _code = nodecode.ChildNodes[0].Value;
                    _address = nodeaddress.ChildNodes[0].Value;
                    _number = nodenumber.ChildNodes[0].Value;

                    Phone phone = new Phone(_name, _code, _address, _number);
                    listphone.Add(phone);
                    i++;
                }
                listphone = Sort(listphone);
            return listphone;
        }
        //===========
        // display list => VIEW
        public static void Display(List<Phone> listphone)
        {
            int i=0;
            if (listphone.Count > 0)
            {
                Console.WriteLine();
                Console.WriteLine("-------------------------------------------------------------------------------");
                Console.WriteLine(string.Format(" {0,-3} | {1,-20} | {2,-5} | {3,-25} | {4,-10}", "STT", "Name ", "Code", "Address", "Number phone"));
                Console.WriteLine("-------------------------------------------------------------------------------");
                foreach (Phone phone in listphone)
                {
                    Console.WriteLine(string.Format(" {0,-3} | {1,-20} | {2,-5} | {3,-25} | {4,-10}", i + 1, phone.Name, phone.Code, phone.Address, phone.Number));
                    i++;
                }
            }
            else
                Console.WriteLine("\nDanh sach rong");
        }

        // display sortelist => VIEW
        public static void Display(SortedList<int, Phone> s_listphone)
        {
            if (s_listphone.Count > 0)
            {
                Console.WriteLine();
                Console.WriteLine("-------------------------------------------------------------------------------");
                Console.WriteLine(string.Format(" {0,-3} | {1,-20} | {2,-5} | {3,-25} | {4,-10}", "STT", "Name ", "Code", "Address", "Number phone"));
                Console.WriteLine("-------------------------------------------------------------------------------");

                for (int i = 0; i < s_listphone.Count; i++)
                    Console.WriteLine(string.Format(" {0,-3} | {1,-20} | {2,-5} | {3,-25} | {4,-10}", i + 1, s_listphone[i].Name, s_listphone[i].Code, s_listphone[i].Address, s_listphone[i].Number));
            }
            else
                Console.Write(" Khong tin thay thue bao!");
        }
        //==================
        // search subscribers with name input from keyboard
        static public SortedList<int,Phone> SearchName(List<Phone> listphone)
        {
            SortedList<int, Phone> S_listphone = new SortedList<int, Phone>();
            string _name; 
            int i=0;
            Console.Write("Nhap ten thue bao can tim:"); _name = Console.ReadLine();
            foreach (Phone phone in listphone)
            {
                if (phone.Name.Contains(_name))
                {
                    S_listphone.Add(i, phone);
                    i++;                }
            }
            return S_listphone;
        }

        //==================
        // search subscribers with phone number input from keyboard
        static public SortedList<int, Phone> SearchNumber(List<Phone> listphone)
        {
            SortedList<int, Phone> S_listphone = new SortedList<int, Phone>();
            string _number;
            int i = 0;
            Console.Write("Nhap so dien thoai can tim can tim:"); _number = Console.ReadLine();
            foreach (Phone phone in listphone)
            {
                if (phone.Number.Contains(_number))
                {
                    S_listphone.Add(i, phone);
                    i++;
                }
                
            }
            return S_listphone;
        }
        //==============================================
        static SortedList<int,Phone> FuntionSearchName(List<Phone> listphone)
        {
            SortedList<int, Phone> S_listphone = new SortedList<int, Phone>();
            S_listphone = SearchName(listphone);
            Display(S_listphone);
            return S_listphone;
        }
        static SortedList<int, Phone> FuntionSearchNumber(List<Phone> listphone)
        {
            SortedList<int, Phone> S_listphone = new SortedList<int, Phone>();
            listphone = XmlToList(filename);
            S_listphone =SearchNumber(listphone);
            Display(S_listphone);
            return S_listphone;
        }
        //===============
        static void FuntionEdit(SortedList<int, Phone> S_listphone, List<Phone> listphone)
        {
            if (S_listphone.Count < 1)
            {
                Console.ReadKey();
                Console.Clear();
                Menu();
            }
            else
            {
                int count = 0;
                string _Name, _Code, _Address, _Number, choose, oldarray;
                Console.Write(" chon so thu tu cua thue bao can sua:");
                try
                {
                    do
                    {
                        if (count > 0)
                            Console.Write("\tChon sai, chon lai:");
                        pos = Convert.ToInt32(Console.ReadLine());
                        count++;
                    }
                    while ((pos > S_listphone.Count) || (pos < 0));
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex);
                }
                listphone.Remove(S_listphone[pos - 1]);              
                oldarray = insertdata("edit",listphone);
                string[] array = oldarray.Split(',');

                _Name = array[0];
                _Code = array[1];
                _Address = array[2];
                _Number = array[3];
                if (_Name.Length == 0)
                    _Name = S_listphone[pos - 1].Name;
                if (_Code.Length == 0)
                    _Code = S_listphone[pos - 1].Code;
                if (_Address.Length == 0)
                    _Address = S_listphone[pos - 1].Address;            
                Console.Write("Ban co dong y sua khong(Y/N)?:");
                choose = Console.ReadKey().KeyChar.ToString();
                if ((choose == "y") || (choose == "Y"))
                {
                    Phone phone = new Phone(_Name, _Code, _Address, _Number);
                    listphone.Add(phone);
                    
                    CreateFile();
                    ListToXml(listphone);
                    Console.WriteLine("\n sua thue bao thanh cong");
                }
                if ((choose == "n") || (choose == "N"))
                {
                    listphone.Add(S_listphone[pos - 1]);
                    Console.Clear();
                    Menu();
                }
            }
        }
        //================sai kiem tra khi khong ton tai
       
        //==========================
        // delete element and add infomations new into file xml
        static void FuntionDelete(SortedList<int, Phone> S_listphone, List<Phone> listphone)
        {
            string choose;
            int count = 0;
            if (S_listphone.Count < 1)
            {
                Console.ReadKey();
                Console.Clear();
                Menu();
            }
            else
            {
                Console.Write(" chon so thu tu cua thue bao can xoa:");
                do
                {
                    try
                    {
                        if (count > 0)
                            Console.Write("Chon sai, chon lai:");
                        count++;
                        pos = Convert.ToInt32(Console.ReadLine());
                    }
                    catch (Exception ex)
                    {
                    }
                }
                while (pos > S_listphone.Count || pos < 1);


                Console.Write(" Ban co dong y xoa khong(Y/N)?:");
                choose = Console.ReadKey().KeyChar.ToString();
                if ((choose == "y") || (choose == "Y"))
                {
                    listphone.Remove(S_listphone[pos - 1]);
                    CreateFile();
                    ListToXml(listphone);
                    Console.WriteLine("\n xoa thue bao thanh cong");
                }
                if ((choose == "n") || (choose == "N"))
                {
                    Console.Clear();
                    Menu();
                }
            }
        }
        //===========
        public static List<Phone> Sort(List<Phone> listphone)
        {
            try
            {
                listphone.Sort(Compare);
            }
            catch (Exception ex)
            {
               // Console.WriteLine(ex);
            }  
            return listphone;
        }
        public static int Compare(Phone x, Phone y)
        {
            string lastnameX,lastnameY;
            lastnameX = x.Name.Substring(x.Name.LastIndexOf(' ') + 1);
            lastnameY = y.Name.Substring(y.Name.LastIndexOf(' ') + 1);
            //return x.Name.CompareTo(y.Name);
            if (lastnameX.Equals(lastnameY))
            {
                return x.Name.CompareTo(y.Name);
            }
            return lastnameX.CompareTo(lastnameY);
        }
        //===================================================================================================
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(filename);
            }
            catch (Exception ex)
            {
                CreateFile();   
            }
        lap:
            Menu();
            string ch;
            List<Phone> listphone = new List<Phone>();
            SortedList<int, Phone> S_listphone = new SortedList<int, Phone>();
            ch = Console.ReadLine().ToString();
            switch (ch)
            {
                case "1"://check
                    {
                        Console.Clear();
                        Console.WriteLine(string.Format("{0} : {1}", ch, " Chuc nang them moi thue bao"));
                        FuntionAdd();
                        Console.ReadKey();
                        Console.Clear();
                        goto lap;
                    }
                case "2"://check
                    {
                        Console.Clear();
                        Console.WriteLine(string.Format("{0} : {1}", ch, " Chuc nang sua thong tin thue bao"));
                        Console.Write("\n                -----------------------------------------");
                        Console.Write("\n               |      1. Tim kiem theo ten...            |");
                        Console.Write("\n               |      2. Tim kiem theo so dien thoai...  |");
                        Console.Write("\n                -----------------------------------------");
                        Console.Write("\nChon cach tim kiem:");
                        string choose;
                        listphone = XmlToList(filename);
                        while (1 == 1)
                        {
                            choose = Console.ReadLine();
                            if (choose == "1")
                            {
                                S_listphone = FuntionSearchName(listphone);
                                break;
                            }
                            if (choose == "2")
                            {
                                S_listphone = FuntionSearchNumber(listphone);
                                break;
                            }
                            Console.Write("\t chon sai, chon lai: ");
                        }
                        FuntionEdit(S_listphone,listphone);
                        Console.ReadKey();
                        Console.Clear();
                        goto lap;
                    }
                case "3"://check
                    {
                        Console.Clear();
                        Console.WriteLine(string.Format("{0} : {1}", ch, " Chuc nang xoa thue bao"));
                        Console.Write("\n                -----------------------------------------");
                        Console.Write("\n               |      1. Tim kiem theo ten...            |");
                        Console.Write("\n               |      2. Tim kiem theo so dien thoai...  |");
                        Console.Write("\n                -----------------------------------------");
                        Console.Write("\nChon cach tim kiem:");
                        string choose;
                        listphone = XmlToList(filename);
                        while (1 == 1)
                        {
                            choose = Console.ReadLine();
                            if (choose == "1")
                            {
                                S_listphone = FuntionSearchName(listphone);
                                break;
                            }
                            if (choose == "2")
                            {
                                S_listphone = FuntionSearchNumber(listphone);
                                break;
                            }
                            Console.Write("\t chon sai, chon lai: ");
                        }
                        FuntionDelete(S_listphone,listphone);
                        //Console.ReadKey(); 
                        Console.Clear();
                        goto lap;
                    }
                case "4"://check
                    {
                        Console.Clear();
                        Console.WriteLine(string.Format("{0} : {1}", ch, " Chuc nang tim kiem theo ten thue bao"));
                        listphone = XmlToList(filename);
                        S_listphone = FuntionSearchName(listphone);
                        S_listphone.Clear();
                        Console.ReadKey();
                        Console.Clear();
                        goto lap;
                    }
                case "5"://check
                    {
                        Console.Clear();
                        Console.WriteLine(string.Format("{0} : {1}", ch, " Chuc nang tim kiem theo so dien thoai"));
                        listphone = XmlToList(filename);
                        FuntionSearchNumber(listphone);
                        Console.ReadKey();
                        Console.Clear();
                        goto lap;
                    }
                case "6"://check
                    {

                        listphone = XmlToList(filename);
                        Console.Clear();
                        Console.WriteLine(string.Format("{0} : {1}", ch, " Chuc nang xem thong tin danh ba"));
                        Display(listphone);
                        Console.WriteLine();
                        Console.Write(" Enter de quay lai Menu!");
                        Console.ReadKey();
                        Console.Clear();
                        goto lap;
                    }
                case "7": break;//check
                default://check
                    {
                        Console.Write("Chuc nang khong dung!");
                        Console.ReadKey();
                        Console.Clear();
                        goto lap;
                    }
            }
        }
    }
}
